package com.nononsenseapps.feeder.sync.local.source.sms

import android.annotation.SuppressLint
import android.content.Context
import android.database.sqlite.SQLiteException
import android.provider.Telephony
import com.nononsenseapps.feeder.db.DEFAULT
import com.nononsenseapps.feeder.parser.Author
import com.nononsenseapps.feeder.parser.Feed
import com.nononsenseapps.feeder.parser.Item
import org.joda.time.LocalDateTime
import timber.log.Timber
import java.util.*

object SmsSource {

    const val SMS_PATH="/context/sms/"

    /*val  SMS_URI_ALL = "content://sms" // 所有短信
    val SMS_URI_INBOX = "content://sms/inbox" // 收件箱
    val SMS_URI_SEND = "content://sms/sent" // 已发送
    val SMS_URI_DRAFT = "content://sms/draft" // 草稿
    val SMS_URI_OUTBOX = "content://sms/outbox" // 发件箱
    val SMS_URI_FAILED = "content://sms/failed" // 发送失败
    val SMS_URI_QUEUED = "content://sms/queued" // 待发送列表*/


    @SuppressLint("Range")
    suspend fun fetchFeedForSms(feedSql: com.nononsenseapps.feeder.db.entity.Feed,
                                phoneNumber:String,
                                context: Context
    ): Feed?{
        var builderFeed: Feed?=null
        val feedItems= mutableListOf<Item>()
        try {
            val projection =  arrayOf( Telephony.Sms._ID,
                Telephony.Sms.ADDRESS,
                Telephony.Sms.PERSON,
                Telephony.Sms.BODY,
                Telephony.Sms.DATE,
                Telephony.Sms.TYPE,
                Telephony.Sms.THREAD_ID,
                Telephony.Sms.SUBJECT,
                Telephony.Sms.CREATOR
            )

            val selection =if(phoneNumber.isNullOrEmpty()) null else "${Telephony.Sms.ADDRESS}=${phoneNumber}"
            val cur = context.contentResolver.query(Telephony.Sms.CONTENT_URI, projection, selection,
                null, Telephony.Sms.Inbox.DEFAULT_SORT_ORDER) // 获取手机内部短信
            // 获取短信中最新的未读短信
            // Cursor cur = getContentResolver().query(uri, projection,
            // "read = ?", new String[]{"0"}, "date desc")

            Timber.d("read sms:${Telephony.Sms.CONTENT_URI} filter:$selection cols:${cur?.columnNames?.joinToString()}")

            val feedUrl= buildUrl(phoneNumber)

            if (cur != null) {
                if (cur.moveToFirst()) {
                    val index_id =  cur.getColumnIndex(projection[0])
                    val index_Address = cur.getColumnIndex(projection[1])
                    val index_Person = cur.getColumnIndex(projection[2])
                    val index_Body = cur.getColumnIndex(projection[3])
                    val index_Date = cur.getColumnIndex(projection[4])
                    val index_Type = cur.getColumnIndex(projection[5])

                    do {
                        val id = cur.getString(index_id)
                        val strAddress = cur.getString(index_Address);
                        val intPerson = cur.getInt(index_Person);
                        val strbody = cur.getString(index_Body);
                        val longDate = cur.getLong(index_Date);
                        val intType = cur.getInt(index_Type);

                        val strDate = LocalDateTime.fromDateFields(Date(longDate)).toString()

                        var strType = when(intType){
                            Telephony.Sms.MESSAGE_TYPE_INBOX-> "接收"
                            Telephony.Sms.MESSAGE_TYPE_SENT -> "发送"
                            Telephony.Sms.MESSAGE_TYPE_DRAFT -> "草稿"
                            Telephony.Sms.MESSAGE_TYPE_OUTBOX -> "发件箱"
                            Telephony.Sms.MESSAGE_TYPE_FAILED -> "发送失败"
                            Telephony.Sms.MESSAGE_TYPE_QUEUED -> "待发送列表"
                            Telephony.Sms.MESSAGE_TYPE_ALL -> "所以短信"
                            else -> {""}
                        }
                        val itemUrl= "$feedUrl&id=$id"

                        val item= Item(
                        id=itemUrl,
                        title = "[$strType]$strbody",
                        url= itemUrl,
                        content_html=strbody,
                        author = Author(name = strAddress),
                        date_published=strDate,
                        date_modified =strDate
                        )
                        feedItems.add(item)
                        Timber.d("read from sms:Telephony.Sms.ADDRESS-${cur.getString(cur.getColumnIndex(
                            Telephony.Sms.ADDRESS))}")
                        Timber.d("read from sms:THREAD_ID-${cur.getString(cur.getColumnIndex(Telephony.Sms.THREAD_ID))}")
                        Timber.d("read from sms:SUBJECT-${cur.getString(cur.getColumnIndex(Telephony.Sms.SUBJECT))}")
                        Timber.d("read from sms:CREATOR-${cur.getString(cur.getColumnIndex(Telephony.Sms.CREATOR))}")
                    } while (cur.moveToNext())

                    if (!cur.isClosed) {
                        cur.close()
                    }
                    builderFeed= Feed(title=phoneNumber,
                        feed_url=feedUrl,
                        items=feedItems,
                        responseHash = UUID.randomUUID().hashCode()
                    )
                }
            }
        } catch ( ex: SQLiteException) {
            Timber.d("SQLiteException in getSmsInPhone  ${ex.message}");
        }

        return builderFeed
    }

    fun buildUrl(phoneNumber: String)=DEFAULT.SOURCE_URL+SMS_PATH+"?"+phoneNumber
}